package com.jhd.fuzhou.view.document;

import androidx.annotation.NonNull;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.github.barteksc.pdfviewer.PDFView;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.EPrinterService;
import com.jhd.fuzhou.service.PDFService;
import com.jhd.fuzhou.service.PrinterService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.DateTime;
import com.jhd.fuzhou.util.DocumentPreview;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.util.UploadSign;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.vo.DocumentNoClaimVo;
import com.jhd.fuzhou.vo.JsonForResult;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


/*文书管理预览打印页面*/
public class DocumentPrintActivity extends BaseActivity {
    private String url,name;//模板url
    @BindView(R.id.pdfView)PDFView pdfView;
    private Context context = this;
    private ProgressDialog _dialog;
    @BindView(R.id.btn_print)Button btn_print;
    private PrinterService printerService;
    private EPrinterService ePrinterService;
    private String bh;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_document_preview);
    }

    @Override
    protected void processLogic() {
        onBack();
       // application.addDocActivity(this);
        url=getIntent().getStringExtra("url");
        name=getIntent().getStringExtra("name");
        findViewById(R.id.tv_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //application.exitDoc();
                finish();
            }
        });
        if(UtilHelper.ePrinterType==0){
            printerService = new PrinterService.Builder(this).build();
        }else{
            ePrinterService=new EPrinterService.Builder(this).build();
        }
        _dialog = new ProgressDialog(context);
        _dialog.setMessage("正在生成文书,请稍等...");
        _dialog.show();
        takeDocumentNo(1);

    }

    @OnClick({R.id.btn_download, R.id.btn_print})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_download:
                if(bh==null){
                    CustomToast.showText(context,"未获取到文书编号,请稍等",3000,0,0).show();
                }else{
                    UploadFile.copyFile(getExternalFilesDir(null).getPath() + "/Download/document.pdf",
                            getExternalFilesDir(null).getPath() + "/Download/文书管理/",name+bh+ ".pdf", context);
                }
                break;
            case R.id.btn_print:
                if(UtilHelper.ePrinterType==0) {
                    printerService.executePrint(btn_print);
                }else {
                    ePrinterService.executePrint(btn_print);
                }
                break;
        }
    }

    /*获取文书编号*/
    private void takeDocumentNo(int type){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        PDFService vs = retrofit.create(PDFService.class);
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("claimDeptId",(application.getDeptId()==null)?"":application.getDeptId());
        params.put("docType","日常监督文书");
        if(bh!=null)params.put("documentNo",bh.substring(5));
        Call<JsonForResult> jsonForResultCall = vs.takeDocumentNo(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){
                            if(type==1){
                                documentNoClaimVo= JSON.parseObject(jsonForResult.getData().toString(), DocumentNoClaimVo.class);
                                bh= DateTime.getYear()+"-"+String.valueOf(documentNoClaimVo.getCurrentNo());
                                exportInquiryRecordPDF();
                            }
                        }else{
                            if(jsonForResult.getMessage()!=null){
                                //CustomToast.showText(context,jsonForResult.getMessage(),3000,0,0).show();
                            }
                        }
                    }else if(jsonForResult!=null&&!jsonForResult.isSuccess()&&jsonForResult.getMessage()!=null){
                        CustomToast.showText(context,jsonForResult.getMessage(),3000,0,0).show();
                    }
                } catch (Exception e) {
                    _dialog.dismiss();
                    CustomToast.showText(context,e.getMessage(),3000,0,0).show();
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                String msg = "获取文书编号失败!";
                _dialog.dismiss();
                CustomToast.showText(context, "获取文书编号失败!",3000,0,0).show();
            }
        });
    }
    private void exportInquiryRecordPDF() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        PDFService vs = retrofit.create(PDFService.class);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), DocumentPreview.superviseOpinion(application,bh, url));
        Call<ResponseBody> jsonForResultCall = vs.exportSuperviseOpinionPDF(application.getAccessToken(), requestBody);
        jsonForResultCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    _dialog.dismiss();
                    if (response.code() == 200) {
                        InputStream inputStream = response.body().byteStream();
                        //保存本地
                        writeResponseBodyToDisk(inputStream);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                String msg = "制作文书失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });

    }
    private void writeResponseBodyToDisk(InputStream inputStream) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String fileName = "Download/document.pdf";//文件名
                File dir = new File(getExternalFilesDir(null).getPath() + "/Download/");//路径
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(getExternalFilesDir(null).getPath() + "/" + fileName);
                try {
                    int index;
                    byte[] bytes = new byte[1024];
                    FileOutputStream outputStream = new FileOutputStream(file);
                    while ((index = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, index);
                    }
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                    handler.sendEmptyMessage(3);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 3) {//上传文书和显示
                File file = new File(getExternalFilesDir(null).getPath() + "/Download/document.pdf");
                if (_dialog != null) _dialog.cancel();
                takeDocumentNo(2);//文书号占用
                UploadFile.showPDF(pdfView, file, context);
            }
        }
    };
}